package org.itboys.mobile.controller.weixin;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.pay.SundayPayProductMapper;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.pay.SundayPayProduct;
import org.itboys.mobile.service.mongo.weixin.SundayWeiXinMemberService;
import org.itboys.mobile.service.mysql.weixin.SundayWeiXinPayService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.itboys.pay.weixin.JsPaySignTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017年5月9日
 * 描述：众包_微信_支付_controller
 */
@Controller
@RequestMapping("/sunday/weixin/pay")
public class SundayWeiXinPayController extends BaseController{

    @Autowired
    private SundayPayProductMapper payProductMapper;
    @Autowired
    private SundayWeiXinPayService payService;



    /**
     * 支付
     * @param request
     * @param response
     */
    @RequestMapping(value="/index", method= RequestMethod.GET)
    @ApiOperation(value="支付页面")
    public String member_step1(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model
            ){
        try{
            //获取充值产品
            Map<String,Object> param = new HashMap<String,Object>();
            List<SundayPayProduct> payProducts = payProductMapper.select(param);
            model.addAttribute("products",payProducts);
            return "/zhongbao/weixin/pay/index";
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/pay/index----e="+e.getMessage());

            }
            e.printStackTrace();
            return "/zhongbao/wexin/error";
        }
    }


    /**
     * 微信支付-统一下单
     * @param request
     * @param productId
     * @param response
     */
    @RequestMapping("/preparePay")
    public  void preparePay(HttpServletRequest request,
                         @RequestParam(value="productId",required = true) Long productId,
                         HttpServletResponse response){

        try {
            SundayMemberSessionDto memberSessionDto=AccountIdHoldUtils.getSessionMember(request);
            JsPaySignTool tool=payService.preparePay(request, memberSessionDto.getId(), productId);
            ResponseMessage.success(tool);
        } catch (Exception e) {
            String msg =CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/pay/preparePay----e="+e.getMessage());

            }
            e.printStackTrace();
        }
    }
    //微信支付后回掉
    @RequestMapping(value="/callback/wechat", method=RequestMethod.POST)
    public  void callback_wechat(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            String reuslt =payService.callback_wechat(request);
            AjaxUtils.renderJson(response, reuslt);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("/sunday/weixin/pay/callback/wechat------"+e.getMessage());
            AjaxUtils.renderJson(response, "fail");
        }
    }

}
